package biz

import (
	"context"
	"fmt"

	pb "manage/api/class"

	"github.com/Fromsko/gouitls/logs"
	"github.com/go-kratos/kratos/v2/log"
)

var echo = logs.InitLogger()

func NewClassUsecase(repo ClassRepo, logger log.Logger) *ClassUsecase {
	return &ClassUsecase{repo: repo, log: log.NewHelper(logger)}
}

// NOTE: 创建班级(业务)
func (c *ClassUsecase) Create(ctx context.Context, req *pb.CreateClassRequest) (*pb.CreateClassResponse, error) {
	echo.Info("创建请求")

	resp, err := c.repo.CreateClass(&CreateClassRequest{
		ClassName: req.ClassName,
		TeacherID: req.TeacherId,
	})

	reply := &pb.CreateClassResponse{
		Code: 200,
	}

	if err != nil {
		reply.Code = 400
		reply.Msg = err.Error()
		if resp != nil {
			reply.ClassId = resp.ClassID
		}
	} else {
		reply.Msg = resp.Message
		reply.ClassId = resp.ClassID
	}

	return reply, nil
}

// NOTE: 删除班级(业务)
func (s *ClassUsecase) Delete(ctx context.Context, req *pb.DeleteClassRequest) (*pb.DeleteClassResponse, error) {
	reply := &pb.DeleteClassResponse{
		Code: 200,
		Msg:  "删除成功",
	}

	echo.Info("删除请求")

	if err := s.repo.DeleteClass(req.ClassId); err != nil {
		reply.Code = 400
		reply.Msg = fmt.Sprintf("删除失败:%v", err)
	}

	return reply, nil
}

// NOTE: 更新班级(业务)
func (s *ClassUsecase) Update(ctx context.Context, req *pb.UpdateClassRequest) (*pb.UpdateClassResponse, error) {
	reply := &pb.UpdateClassResponse{
		Code: 200,
		Msg:  "更新成功",
	}

	echo.Info("更新请求")

	if err := s.repo.UpdateClass(&CreateClassRequest{
		ClassName: req.ClassName,
		TeacherID: req.TeacherId,
	}, req.ClassId); err != nil {
		reply.Code = 400
		reply.Msg = fmt.Sprintf("更新失败:%v", err)
	}

	return reply, nil
}

// NOTE: 查询班级(业务)
func (s *ClassUsecase) Get(ctx context.Context, req *pb.GetClassRequest) (*pb.GetClassResponse, error) {
	reply := &pb.GetClassResponse{
		Code: 200,
		Msg:  "查询成功",
	}

	echo.Info("查询请求")

	if info, err := s.repo.GetClassInfo(req.ClassId); err != nil {
		reply.Code = 400
		reply.Msg = fmt.Sprintf("查询失败:%v", err)
	} else {
		reply.ClassInfo = &pb.ClassInfo{
			TeacherId: info.TeacherID,
			ClassName: info.ClassName,
			ClassId:   info.ClassID,
		}
	}

	return reply, nil
}
